import { Button, Modal, Form, Input, Select } from 'antd';
import { useEffect, useState } from 'react';
import axios from '../../aixos';
import { connect } from 'react-redux'
import Table from '../../components/Table/Table'

const { Option } = Select;



function List(props) {

  const [pageIndex, setPageIndex] = useState(1)
  const [collectionList, setCollectionList] = useState([])
  const pageSize = 10
  const [total, setTotal] = useState(0)
  const [modalTitle, setModalTitle] = useState(null)


  const [categoryList, setCategoryList] = useState([])

  const columns = [
    {
      title: '分类',
      dataIndex: 'category',
      render: category => <span>{category.name}</span>,
      filters: categoryList.map(item => {
        return { value: item._id, text: item.name }
      }),
      onFilter: (value, record) => {
        console.log(value, record)
        return record.category._id === value
      }
    },
    {
      title: '名称',
      dataIndex: 'name',
      render: text => <span>{text}</span>,
    },
    {
      title: '描述',
      dataIndex: 'description'
    },
    {
      title: 'logo',
      dataIndex: 'imageUrl',
      render: (val) => {
        return <img style={{maxWidth: '150px'}} src={val} alt="图片飞走了" />
      }
    },
    {
      title: '链接',
      dataIndex: 'url',
      render: (url) => {
        return <a href={url}>{url}</a>
      }
    }
  ];

  useEffect(() => {
    axios.get('/collection', {
      pageIndex,
      pageSize
    }).then(res => {
      setCollectionList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex])

  useEffect(() => {
    axios.get('/collection/category').then(res => {
      setCategoryList(res.data)
    })
  }, [])

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editRecordId, setEditRecordId] = useState(null)


  const showModal = () => {
    form.resetFields()
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleOk = async () => {
    console.log(form)
    const formData = await form.validateFields()
    

    if (!editRecordId) {
      axios.post('/collection', formData).then(res => {
        setIsModalVisible(false)
        setCollectionList([res.data, ...collectionList])
      })
    } else {
      axios.put('/collection', {
        id: editRecordId,
        ...formData
      }).then(() => {
        setCollectionList(collectionList.map(item => {
          if (item._id === editRecordId) return { ...item, ...formData } 
          return item
        }))
        setIsModalVisible(false)
      })
    }
  };
  const changePage = (index) => {
    console.log(index)
    setPageIndex(index)
  }
  const del = (id) => {
    axios.delete('/collection', {
      id
    }).then(() => {
      setCollectionList(collectionList.filter((item) => {
        return item._id !== id
      }))
      setTotal(total - 1)
    })
  }
  const edit = (record) => {
    setModalTitle('编辑')
    setEditRecordId(record._id)
    form.setFieldsValue({...record})
    setIsModalVisible(true)
  }
  const [form] = Form.useForm();
  return (
    <>
      <Table columns={columns} rowKey='_id' dataSource={collectionList} pagination={{
        current: pageIndex,
        pageSize: pageSize,
        total: total,
        showTotal: () => `共 ${total} 条数据`,
        onChange: changePage
      }} 
      action={{
        edit: {callback: edit},
        delete: {callback: del}
      }}
      >
        <Button type='primary' onClick={showModal}>添加收藏</Button>
      </Table>
      <Modal title={modalTitle} cancelText='取消' okText='确认'
        visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="分类"
            name="category"
            rules={[
              {
                required: true,
                message: '请选择分类',
              },
            ]}
          >
            <Select style={{ width: 120 }} placeholder='请选择分类'>
              {
                categoryList?.map((item) => {
                  return <Option value={item._id} key={item._id}>{item.name}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item
            label="名称"
            name="name"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="描述"
            name="description"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="logo"
            name="imageUrl"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="链接"
            name="url"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default connect((state) => {
  return {
    roleType: state.state.roleType,
    userState: state.state.userState
  }
})(List);